package com.shop.zkmall.app.service.a.impl;

import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.zkmall.app.dao.buyer.CereBuyerReceiveDAO;
import com.shop.zkmall.app.dao.order.CereShopOrderDAO;
import com.shop.zkmall.app.dao.product.CereShopProductDAO;
import com.shop.zkmall.app.dao.shop.CereShopCommentDAO;
import com.shop.zkmall.app.domain.CereShopMarketing;
import com.shop.zkmall.app.domain.LiveRoomGoods;
import com.shop.zkmall.app.domain.req.*;
import com.shop.zkmall.app.domain.res.ProductDetail;
import com.shop.zkmall.app.mapper.CereShopMarketingMapper;
import com.shop.zkmall.app.mapper.LiveRoomGoodsMapper;
import com.shop.zkmall.app.service.a.ICereShopMarketingService;
import com.shop.zkmall.app.utils.LoginHelper;
import com.shop.zkmall.app.utils.OrderNumUtils;
import com.shop.zkmall.commons.domain.buyer.CereBuyerReceive;
import com.shop.zkmall.commons.domain.order.CereShopOrder;
import com.shop.zkmall.commons.domain.product.CereShopProduct;
import com.shop.zkmall.commons.domain.shop.CereShopComment;
import com.shop.zkmall.commons.exception.CoBusinessException;
import com.shop.zkmall.commons.result.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 统一商品营销活动表（免费/砍价/竞拍/闪购） 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2025-11-27
 */
@Service
public class CereShopMarketingServiceImpl extends ServiceImpl<CereShopMarketingMapper, CereShopMarketing> implements ICereShopMarketingService {

    @Autowired
    private CereShopProductDAO shopProductDAO;
    @Autowired
    private CereShopCommentDAO shopCommentDAO;
    @Autowired
    private CereBuyerReceiveDAO cereBuyerReceiveDAO;
    @Autowired
    private LiveRoomGoodsMapper liveRoomGoodsMapper;
    @Autowired
    private CereShopOrderDAO cereShopOrderDAO;

    @Override
    public R<?> addShopMarketingProduct(CereShopMarketingReq cereShopMarketingReq) {
        //先添加商品
        CereShopProduct cereShopProduct = new CereShopProduct();
        cereShopProduct.setProductName(cereShopMarketingReq.getProductName());
        cereShopProduct.setProductImage(cereShopMarketingReq.getProductImage());
        cereShopProduct.setClassifyId(cereShopMarketingReq.getProductCategoryId());
        cereShopProduct.setProductText(cereShopMarketingReq.getProductIntroduce());
        cereShopProduct.setShopId(cereShopMarketingReq.getShopId());
        shopProductDAO.insertSelective(cereShopProduct);

        //添加活动记录
        CereShopMarketing cereShopMarketing = new CereShopMarketing();
        cereShopMarketing.setActivityType(cereShopMarketingReq.getActivityType());
        cereShopMarketing.setGoodsId(cereShopProduct.getProductId());
        cereShopMarketing.setShopId(cereShopMarketingReq.getShopId());
        cereShopMarketing.setOriginalPrice(cereShopMarketingReq.getOriginalPrice());
        cereShopMarketing.setActivityPrice(cereShopMarketingReq.getActivityPrice());
        cereShopMarketing.setBargainTargetPrice(cereShopMarketingReq.getBargainTargetPrice());
        cereShopMarketing.setStartPrice(cereShopMarketingReq.getStartPrice());
        cereShopMarketing.setAddPrice(cereShopMarketingReq.getAddPrice());
        cereShopMarketing.setBuyoutPrice(cereShopMarketingReq.getBuyoutPrice());
        cereShopMarketing.setBuyoutStock(cereShopMarketingReq.getBuyoutStock());
        cereShopMarketing.setFreightType(cereShopMarketingReq.getFreightType());
        cereShopMarketing.setStatus(1);
        this.save(cereShopMarketing);

        return R.ok();
    }

    @Override
    public R<?> batchOnLine(BatchOnLineReq batchOnLineReq) {
        lambdaUpdate().eq(CereShopMarketing::getActivityType, batchOnLineReq.getActivityType())
                .eq(CereShopMarketing::getShopId, batchOnLineReq.getShopId())
                .in(CereShopMarketing::getGoodsId, batchOnLineReq.getIds())
                .set(CereShopMarketing::getStatus, batchOnLineReq.getType())
                .update();
        return R.ok();
    }

    @Override
    public R<?> productList(ProductListReq productListReq) {
        Page<CereShopMarketing> page = new Page<>(productListReq.getPage(), productListReq.getPageSize());
        Page<CereShopMarketing> res = lambdaQuery().eq(CereShopMarketing::getActivityType, productListReq.getActivityType())
                .eq(CereShopMarketing::getShopId, productListReq.getShopId())
                .eq(CereShopMarketing::getStatus, productListReq.getType())
                .eq(CereShopMarketing::getActivityType, productListReq.getActivityType())
                .orderByDesc(CereShopMarketing::getCreateTime)
                .page(page);
        return R.ok(res);
    }

    @Override
    public R<?> editProduct(EditCereShopMarketingReq editCereShopMarketingReq) {

        //更新商品表
        CereShopProduct cereShopProduct = new CereShopProduct();
        cereShopProduct.setProductId(editCereShopMarketingReq.getGoodsId());
        cereShopProduct.setProductName(editCereShopMarketingReq.getProductName());
        cereShopProduct.setProductImage(editCereShopMarketingReq.getProductImage());
        cereShopProduct.setProductText(editCereShopMarketingReq.getProductIntroduce());
        cereShopProduct.setClassifyId(editCereShopMarketingReq.getProductCategoryId());
        shopProductDAO.updateById(cereShopProduct);


        lambdaUpdate().eq(CereShopMarketing::getActivityType, editCereShopMarketingReq.getActivityType())
                .eq(CereShopMarketing::getShopId, editCereShopMarketingReq.getShopId())
                .eq(CereShopMarketing::getGoodsId, editCereShopMarketingReq.getGoodsId())
                .set(editCereShopMarketingReq.getActivityType()!=null,CereShopMarketing::getActivityType, editCereShopMarketingReq.getActivityType())
                .set(editCereShopMarketingReq.getOriginalPrice()!=null,CereShopMarketing::getOriginalPrice, editCereShopMarketingReq.getOriginalPrice())
                .set(editCereShopMarketingReq.getActivityPrice()!=null,CereShopMarketing::getActivityPrice, editCereShopMarketingReq.getActivityPrice())
                .set(editCereShopMarketingReq.getBargainTargetPrice()!=null,CereShopMarketing::getBargainTargetPrice, editCereShopMarketingReq.getBargainTargetPrice())
                .set(editCereShopMarketingReq.getStartPrice()!=null,CereShopMarketing::getStartPrice, editCereShopMarketingReq.getStartPrice())
                .set(editCereShopMarketingReq.getAddPrice()!=null,CereShopMarketing::getAddPrice, editCereShopMarketingReq.getAddPrice())
                .set(editCereShopMarketingReq.getBuyoutPrice()!=null,CereShopMarketing::getBuyoutPrice, editCereShopMarketingReq.getBuyoutPrice())
                .set(editCereShopMarketingReq.getBuyoutStock()!=null,CereShopMarketing::getBuyoutStock, editCereShopMarketingReq.getBuyoutStock())
                .set(editCereShopMarketingReq.getFreightType()!=null,CereShopMarketing::getFreightType, editCereShopMarketingReq.getFreightType())
                .update();
        return R.ok();
    }

    @Override
    public R<?> productDetail(productDetailReq productDetailReq) {
        ProductDetail productDetail = new ProductDetail();
        LambdaQueryWrapper<CereShopProduct> cereShopProductLambdaQueryWrapper = new LambdaQueryWrapper<>();
        cereShopProductLambdaQueryWrapper.in(CereShopProduct::getProductId,productDetailReq.getProductId());
        CereShopProduct cereShopProduct = shopProductDAO.selectOne(cereShopProductLambdaQueryWrapper);
        if (cereShopProduct == null){
            return R.fail("商品不存在");
        }

        //查询商品评价
        LambdaQueryWrapper<CereShopComment> cereShopCommentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        cereShopCommentLambdaQueryWrapper.eq(CereShopComment::getProductId,productDetailReq.getProductId());
        List<CereShopComment> evaluate = shopCommentDAO.selectList(cereShopCommentLambdaQueryWrapper);

        productDetail.setProductId(cereShopProduct.getProductId());
        productDetail.setProductName(cereShopProduct.getProductName());
        productDetail.setProductImage(cereShopProduct.getProductImage());
        productDetail.setProductIntroduce(cereShopProduct.getProductText());
        //价格
        //productDetail.setOriginalPrice(cereShopProduct.getOriginalPrice());
        //物流
        //productDetail.setDistributionPrice(cereShopProduct.getDistributionPrice());
        productDetail.setEvaluate(evaluate);
        productDetail.setEvaluateCount(evaluate.size());

        return R.ok(productDetail);
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public R<?> createOrder(CreateOrderReq createOrderReq) {
        log.debug("创建订单开始 {}" + createOrderReq);

        //查询商品 库存是否充足
        LambdaQueryWrapper<LiveRoomGoods> liveRoomGoodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        liveRoomGoodsLambdaQueryWrapper.eq(LiveRoomGoods::getGoodsId,createOrderReq.getProductId());
        liveRoomGoodsLambdaQueryWrapper.eq(createOrderReq.getActivityType()!=null,
                 LiveRoomGoods::getType, createOrderReq.getActivityType());
        LiveRoomGoods liveRoomGoods = liveRoomGoodsMapper.selectOne(liveRoomGoodsLambdaQueryWrapper);
        if (liveRoomGoods == null){
            return R.fail("商品不存在");
        }
        if (liveRoomGoods.getStock() < createOrderReq.getCount()){
            return R.fail("库存不足");
        }
        liveRoomGoods.setStock(liveRoomGoods.getStock()-createOrderReq.getCount());
        liveRoomGoods.setSales(liveRoomGoods.getSales()+createOrderReq.getCount());
        liveRoomGoodsMapper.updateById(liveRoomGoods);

        //查询商品信息
        CereShopMarketing product = lambdaQuery().eq(CereShopMarketing::getGoodsId, createOrderReq.getProductId())
                .eq(CereShopMarketing::getShopId, createOrderReq.getShopId())
                .one();


        //计算价格
        BigDecimal total = BigDecimal.ZERO;
        //免费
        if (createOrderReq.getActivityType() == 0){}

        //砍价
        if (createOrderReq.getActivityType() == 1){}

        //竞拍
        if (createOrderReq.getActivityType() == 2){}

        //闪购
        if (createOrderReq.getActivityType() == 3){
            total = product.getActivityPrice();


        }

        CereShopOrder cereShopOrder = new CereShopOrder();
        String orderNo = OrderNumUtils.getInstance().generateOrderNo();
        cereShopOrder.setOrderFormid(orderNo);
        cereShopOrder.setOrderPrice(total);
        cereShopOrder.setPayDelivery(createOrderReq.getPayDelivery());
        cereShopOrder.setPaymentState(0);
        cereShopOrder.setState(0);
        cereShopOrder.setShopId(createOrderReq.getShopId());
        cereShopOrder.setBuyerUserId(LoginHelper.getUserId());

        cereShopOrder.setPrice(total);
        //查询收货地址
        CereBuyerReceive byId = cereBuyerReceiveDAO.getById(createOrderReq.getAddressId());
        if (byId == null){
            return R.fail("收货地址不存在");
        }
        cereShopOrder.setReceiveName(byId.getReceiveName());
        cereShopOrder.setReceivePhone(byId.getReceivePhone());
        cereShopOrder.setReceiveAdress(byId.getReceiveAdress());
        cereShopOrder.setAddress(byId.getAddress());
        cereShopOrder.setProductId(createOrderReq.getProductId());
        int insert = cereShopOrderDAO.insert(cereShopOrder);

        return R.ok(insert);
    }
}
